<?php 
error_reporting(E_ALL);
ini_set("display_errors", "On");
header('Content-Type: text/html; charset=UTF-8');
require 'class_mysql.php';
$c['host'] = '127.0.0.1';
$c['username'] = 'root';
$c['password'] = '';
$c['dbname'] = 'lvzhiwo';
$c['charset'] = 'utf8'; 
$db = new Mysql($c);


function get_cache($name){
	global $db;
	$res = $db->get("SELECT * FROM `cache` WHERE `name` = '$name'");
	return 	isset($res->value)?$res->value:null;
}
function set_cache($name, $value){
	global $db;
	$row = array('name'=>$name, 'value'=>addslashes($value));
	return $db->save('cache', $row);
	
}


$proxy = 'web-proxy.oa.com:8080';
//$proxy = '';
function get_url($url, $proxy=''){

	$flag_write_cache = false;
	$cache_name = $url;
	$cache = get_cache($cache_name);
	if($cache===null){
		
		$flag_write_cache = true;
	}else{
		return $cache;
	};
	$cookie_file = 'cookie.txt';
	$http_code = 302;
	$i = 1; 
	$old_url = $url = $url;
	// create a new cURL resource
	while($http_code=='302' and $i < 6){
		$ch = curl_init();
		// set URL and other appropriate options
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, true);
		curl_setopt ($ch, CURLOPT_REFERER, $old_url);
		if($proxy!=''){
			curl_setopt ($ch, CURLOPT_PROXY, "web-proxy.oa.com:8080");
		}
		curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
		curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt ($ch, CURLOPT_PROXYUSERPWD, '');
		$result = curl_exec($ch);
		if ($result!==false) {
			$info_array = curl_getinfo($ch);
			//判断http_code
			$http_code = $info_array['http_code'];
			$old_url = $url;
			if(isset($info_array['redirect_url'])){
				$url =  $info_array['redirect_url'];
			}else{
				list($header) = explode("\r\n\r\n", $result, 2);
				$matches = array();
				preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
				$url = trim(array_pop($matches));
				$url_parsed = parse_url($url);
				if (isset($url_parsed)) {
					$url = $url;
				}
				
			}
			
		}else{
			die('返回错误:' . curl_error($ch));
		}
		curl_close($ch);
		$i++;
	}
	if($i==6){
		die('获取错误'.$result) ;	
	}
	$result = mb_convert_encoding($result, 'UTF-8','GBK');
	if($flag_write_cache===true){
		set_cache($cache_name, $result);
	}
	return $result;

}

function store_taobao($url, $goods_type, $goods_att_type){
	global $db, $proxy;
	$result = get_url($url, $proxy);


	//取 商品列表
	preg_match_all("/ShopsystemSearchStart(.*)ShopsystemSearchEnd/is", $result, $matches);

	//匹配商品地址
	preg_match_all("/detail\.tmall\.com\/item\.htm\?id\=([0-9]*)\&/is", $matches[0][0], $matches_items);

	//print_r($matches_items);
	foreach($matches_items[0] as $key => $value){
		$addr = 'http://'.$value;
		$item = get_url($addr, $proxy);
		//$goods_sn 为淘宝ITEMID//用来检测产品唯一性；
		preg_match('/id\=([\d]*)/', $value , $id_match);
		$goods_sn = $id_match[1];
		//检查是否已经存在该产品
		$row = $db->get("select * from `ecs_goods` where `goods_sn` = $goods_sn ");
		if($row!==null){
			continue;
		}

		//匹配标题
		if(preg_match('/<title>(.*?)<\/title>/i', $item, $matchs)){
			$item_array['name'] = $matchs[1];
			$item_array['name'] = str_replace('-tmall.com', '', $item_array['name']);
			$item_array['name'] = str_replace('天猫', '', $item_array['name']);
		}else{
			die('标题匹配错误， 地址:'.$addr);
		};

		//匹配标准价格
		if(preg_match('/<strong id\=\"J\_StrPrice\" >(.*)?<\/strong>/i', $item, $matchs)){
			$item_array['normal_price'] = $matchs[1];
		}else{
			die('标准价格匹配错误， 地址:'.$addr);
		};

		//匹配图片
		if(preg_match('/tb\-thumb(.*)J\_ShareParam/is', $item, $matchs)){
			if(preg_match_all('/src\=\"([^"]*?)\"/is', $matchs[0], $matches)){
				$item_array['thumb_pic'] = $matches[1];
			}else{
				die('图片匹配错误， 地址:'.$addr);
			};
		}else{
			die('图片区域匹配错误， 地址:'.$addr);
		};
		
		//匹配描述
		if(preg_match('/http:\/\/dsc([^\']*)\'/is', $item, $matchs)){
			$des = get_url('http://dsc'.$matchs[1], $proxy);
			$des = str_replace('var desc=', '', $des);
			$des = str_replace('\\', '', $des);
			$des = str_replace('\'', '', $des);
			$des = preg_replace('/([^<]*)</is', '', $des, 1);
			$item_array['descript'] = '<'.$des;
		}else{
			die('图片区域匹配错误， 地址:'.$addr);
		};
		//匹配属性
		if(preg_match('/<ul class\=\"attributes-list\">(.*?)<\/ul>/is', $item, $matchs)){
			if(preg_match_all('/<li[^>]*>(.*?)<\/li>/is', $matchs[0], $matches)){
				$item_array['attributes'] = $matches[1];
			}else{
				//die('属性匹配错误， 地址:'.$addr);
			};
		}else{
			//die('属性区域匹配错误， 地址:'.$addr);
		};



		//1.插入产品
		//正常价格 0.85
		$price = $item_array['normal_price']*0.85;

		$goods_thumb = str_replace('_40x40', '_310x310', $item_array['thumb_pic'][0]);
		$goods_img = str_replace('_40x40', '_310x310', $item_array['thumb_pic'][0]);
		$original_img = str_replace('_40x40.jpg', '', $item_array['thumb_pic'][0]);
		
		$goods_thumb = save_image($goods_thumb);
		$goods_img = save_image($goods_img);
		$original_img =save_image($original_img);
		
		$sql = "INSERT INTO `ecs_goods` (goods_name, goods_name_style, goods_sn, cat_id, brand_id, shop_price, market_price, is_promote, promote_price, promote_start_date, promote_end_date, goods_img, goods_thumb, original_img, keywords, goods_brief, seller_note, goods_weight, goods_number, warn_number, integral, give_integral, is_best, is_new, is_hot, is_on_sale, is_alone_sale, is_shipping, goods_desc, add_time, last_update, goods_type, rank_integral, suppliers_id)
		VALUES ('{$item_array['name']}', '', '{$goods_sn}', '{$goods_type}', '2', '{$price}', '{$item_array['normal_price']}', '0','0', '0', '0', '{$goods_img}', '{$goods_thumb}', '{$original_img}', '', '', '', '0', '1', '1', '5', '-1', '0', '0', '0', '1', '1', 0, 
		'{$item_array['descript']}', '1336784233', '1336784233', '0', '-1', '0')";
		
		$db->query($sql);
		
		$good_id = $db->last_insert_id();
		
		//2插入属性
		if(isset($item_array['attributes'])){
			foreach ($item_array['attributes'] as $key => $value){
				$value = str_replace(':', '=', $value);
				$value = str_replace(':', '=', $value);
				$value = str_replace('：', '=', $value);
				
				list($att, $v) = explode("=", $value);
				$att = trim($att);
				//查找 该分类下 有没有该属性，
				//cat_id=1(衣服)	attr_name
				$row = $db->get("select `attr_id` from `ecs_attribute` where `cat_id` = {$goods_att_type} and attr_name LIKE '%$att%'");
				//如果没有该属性 则插入该属性
				if($row === null){
					$db->query("
							INSERT INTO  `ecs_attribute` (`attr_id` , `cat_id` , `attr_name` ,`attr_input_type` ,
							`attr_type` , `attr_values` , `attr_index` ,`sort_order` ,
							`is_linked` , `attr_group`)
							VALUES (NULL ,  '{$goods_att_type}',  '$att',  '0',  '0',  '',  '0',  '0',  '0',  '0')"
					);		
					$attr_id = $db->last_insert_id();
				}else{
					$attr_id = $row->attr_id;
				}
	
				
				$sql = "INSERT INTO `ecs_goods_attr`(goods_attr_id,	goods_id, attr_id, attr_value)
						VALUES (NULL ,  $good_id,  $attr_id,  '$v')
						";
				$db->query($sql);
			}
		}
		//3.插入图片相册
		foreach($item_array['thumb_pic'] as $key => $value){
			$goods_thumb = str_replace('_40x40', '_310x310', $value);
			$goods_img = str_replace('_40x40', '_310x310', $value);
			$original_img = str_replace('_40x40.jpg', '', $value);
			
			$goods_thumb = save_image($goods_thumb);
			$goods_img = save_image($goods_img);
			$original_img =save_image($original_img);
			
			$sql= "INSERT INTO  `ecs_goods_gallery` (
				 `img_id` , `goods_id` , `img_url` ,`img_desc` ,`thumb_url` ,`img_original`)
			VALUES (NULL ,  $good_id,  '$goods_img',  '',  '$goods_thumb',  '$original_img'
			);";
			
			$db->query($sql);	
		}	
	}
}


echo 'success';
//图片 后面 一个个更新
function save_image($url){
	return $url;
}



//单人帐篷
store_taobao('http://searock.tmall.com/search.htm?scid=416620316', 4, 5);
//双日帐篷
store_taobao('http://searock.tmall.com/search.htm?scid=416620317', 4, 5);


//石岩 腰包
store_taobao('http://searock.tmall.com/search.htm?scid=416620310', 25, 6);

store_taobao('http://searock.tmall.com/search.htm?scid=416620312', 25, 6);

//背包
store_taobao('http://searock.tmall.com/search.htm?scid=416620313', 22, 6);
store_taobao('http://searock.tmall.com/search.htm?scid=416620314', 22, 6);
store_taobao('http://searock.tmall.com/search.htm?scid=416620311', 22, 6);

//石岩 羽绒睡袋
store_taobao('http://searock.tmall.com/search.htm?scid=416620305', 29, 4);

//棉睡袋
store_taobao('http://searock.tmall.com/search.htm?scid=416620306', 28, 4);

//信封睡袋
store_taobao('http://searock.tmall.com/search.htm?scid=416620307', 30, 4);

//木乃伊睡袋
store_taobao('http://searock.tmall.com/search.htm?scid=416620308', 31, 4);


//充气垫/防潮垫/地布

store_taobao('http://searock.tmall.com/search.htm?scid=416820652', 6, 7);

//工具
store_taobao('http://searock.tmall.com/search.htm?scid=416620320', 7, 8);
// 灯具
store_taobao('http://searock.tmall.com/search.htm?scid=416620321', 7, 8); 

//工具第二页
store_taobao('http://searock.tmall.com/search.htm?search=y&scid=416620320orderType=_hotsell&pageNum=2', 7, 8);
 //灯具第二页
store_taobao('http://searock.tmall.com/search.htm?search=y&scid=416620321&viewType=grid&orderType=_hotsell&pageNum=2#anchor', 7, 8);

//炉具
store_taobao('http://searock.tmall.com/search.htm?scid=416620322', 7, 8);
// 水具
store_taobao('http://searock.tmall.com/search.htm?scid=416620323', 7, 8);
//帽子
store_taobao('http://searock.tmall.com/search.htm?scid=416620324', 7, 8); 

//登山杖
store_taobao('http://searock.tmall.com/search.htm?scid=416824132', 7, 8); 

//餐具
store_taobao('http://searock.tmall.com/search.htm?scid=416826162', 7, 8); 















//die();


die();

store_taobao('http://sws.tmall.com/search.htm?scid=338909492', 12, 1);
//帐篷
store_taobao('http://sws.tmall.com/search.htm?scid=357885332', 4, 5);
//睡袋
store_taobao('http://sws.tmall.com/search.htm?scid=357885333', 5, 6);
//气垫
store_taobao('http://sws.tmall.com/search.htm?scid=357885334', 6, 7);


//双肩包
store_taobao('http://sws.tmall.com/search.htm?scid=334688866', 22, 4);
//腰包
store_taobao('http://sws.tmall.com/search.htm?scid=334688867', 25, 4);

/*

//沙 滩 鞋
store_taobao('http://sws.tmall.com/search.htm?scid=349386861', 20, 3);
//溯 溪 鞋
store_taobao('http://sws.tmall.com/search.htm?scid=357888214', 19, 3);
//低 帮 鞋
store_taobao('http://sws.tmall.com/search.htm?scid=315322347', 21, 3);
//高 帮 鞋 
store_taobao('http://sws.tmall.com/search.htm?scid=315322346', 18, 3);
*/

//羽绒衣 没有。 
//store_taobao('http://sws.tmall.com/search.htm?scid=420994804', $goods_type, $goods_att_type);
/*
//冲锋衣
store_taobao('http://sws.tmall.com/search.htm?scid=315322343', 8, 1);
//抓绒衣
store_taobao('http://sws.tmall.com/search.htm?scid=315322344', 9 , 1);
//皮肤风衣
store_taobao('http://sws.tmall.com/search.htm?scid=343617907', 13, 1);
//速干衣裤
store_taobao('http://sws.tmall.com/search.htm?scid=357885326', 11, 1);
//全棉Ｔ恤
store_taobao('http://sws.tmall.com/search.htm?scid=338909492', 12, 1);
*/



/*
 	require_once('upyun.class.php');
	$upyun = new UpYun("lvzhiwo", "lvzhiwo", "lvzhiwolvzhiwoXX2A");
	$file = file_get_contents($url);
	$temp_file = 'test.jpg';
	if(file_put_contents($temp_file, $file)!==false){
		$file_handle = fopen($temp_file, 'r');
		$file_name = strrchr($url,'/');
		if($upyun->writeFile('/shop'.$file_name, $file_handle,true)){
			return  'http://lvzhiwo.b0.upaiyun.com/shop' . $file_name;
		}
	};
*/






